import { Component, OnInit, QueryList, ViewChildren } from '@angular/core';
import { DefaultService, Device, Sensor } from '../../api';
import { UserService } from '../user.service';
import { DisplayBox } from '../watcher/display.box';

@Component({
  selector: 'app-data-analysis',
  templateUrl: './data-analysis.component.html',
  styleUrls: ['./data-analysis.component.css']
})
export class DataAnalysisComponent implements OnInit {
  @ViewChildren('box') boxes:QueryList<DisplayBox>;
  selectedChartIndex: number = 0;
  chartsSettings = [
    {type: 'line', class: 'col-lg-3',height:300, title: '折线图(小)'},
    {type: 'line', class: 'col-lg-6',height:300, title: '折线图(中)'},
    {type: 'line', class: 'col-lg-12',height:300, title: '折线图(大)'},
    {type: 'bar', class: 'col-lg-3',height:300, title: '柱状图(小)'},
    {type: 'bar', class: 'col-lg-6',height:300, title: '柱状图(中)'},
    {type: 'bar', class: 'col-lg-12',height:300, title: '柱状图(大)'},
    {type: 'heatmap',class:'col-lg-3',height:300,title:'热力图'},
    {type: 'map',class:'col-lg-12',height:600,title:'地图'}
  ];
  limit: number = 10;
  devices: Device[] = [];
  pageDevice: number = 1;
  maxPageDevice: number;
  selectedDevice: Device = null;

  sensors: Sensor[] = [];
  pageSensor: number = 1;
  maxPageSensor: number;
  selectedSensor: Sensor = null;

  maxData: number;

  options:{clazz:string,name:string,baseType:string,toLoad:boolean,height:number}[]=[];
  removeMode: boolean = false;

  selectedName = "";
  selectedLegend = "";
  disableNameInput = false;

  constructor(public api: DefaultService, public me: UserService) {}

  ngOnInit() {
    this.refreshDevice();
    if(this.me.me==null){
      this.me.meEvent.subscribe(()=>{
        this.load();
      })
    }else{
      this.load();
    }
  }

  refreshDevice() {
    this.api.countDevices().subscribe(value => {
      this.maxPageDevice = Math.ceil(value.count / this.limit);
    });
    this.api.listDevices((this.pageDevice - 1) * this.limit, this.limit).subscribe((devices: Device[]) => {
      this.devices = [];
      devices.forEach(value => {
        try {
          value['image'] = JSON.parse(value.description)['image'];
          console.log(value['image']);
        } catch (e) {
        }
        this.devices.push(value);
      });
    });
  }

  refreshSensor() {
    this.api.countSensors(this.selectedDevice.deviceId).subscribe(value => {
      this.maxPageSensor = Math.ceil(value.count / this.limit);
    });
    this.api.getSensors(this.selectedDevice.deviceId, (this.pageSensor - 1) * this.limit, this.limit).subscribe(value => {
      this.sensors = [];
      value.forEach(v => {
        this.sensors.push(v);
      });
    });
  }

  countData() {
    this.api.countData(this.selectedDevice.deviceId, this.selectedSensor.id).subscribe(value => {
      this.maxData = value.count;
    });
  }

  gotoDevice(page: string | number) {
    if (Number(page) < 1 || Number(page) > this.maxPageDevice) return;
    this.pageDevice = Number(page);
    this.refreshDevice();
  }

  gotoSensor(page: string | number) {
    if (Number(page) < 1 || Number(page) > this.maxPageSensor) return;
    this.pageSensor = Number(page);
    this.refreshSensor();
  }

  addChart(dataOffset: string | number, dataEnd: string | number) {
    const legend = this.selectedLegend;
    const name = this.selectedName;
    const device = this.selectedDevice.deviceId;
    const sensor = this.selectedSensor.id;
    if(this.selectedChartIndex>=this.chartsSettings.length){
      this.boxes.toArray()[this.selectedChartIndex - this.chartsSettings.length]
        .addDataSource(legend,device,Number(sensor),Number(dataOffset),Number(dataEnd)-Number(dataOffset));
    }else {
      const setting = this.chartsSettings[this.selectedChartIndex];
      let subscription;
      subscription = this.boxes.changes.subscribe((list: QueryList<DisplayBox>) => {
        list.last.addDataSource(legend, device, Number(sensor), Number(dataOffset), Number(dataEnd) - Number(dataOffset), setting.type);
        subscription.unsubscribe();
      });
      if(setting.type=='heatmap' || setting.type=='map')
        this.options.push({clazz: setting.class, name: name, baseType: setting.type, toLoad: false,height:setting.height});
      else
        this.options.push({clazz: setting.class, name: name, baseType: 'chart', toLoad: false,height:setting.height});

    }
    this.selectedLegend = "";
    this.selectedName = "";
    this.save();
  }

  onSelected(){
    if(this.selectedChartIndex>=this.chartsSettings.length){
      this.selectedName = this.options[this.selectedChartIndex-this.chartsSettings.length].name;
      this.disableNameInput = true;
    }else{
      this.selectedName = "";
      this.disableNameInput = false;
    }
  }

  clear(){
    this.boxes.forEach(item => {
      item.remove();
    });
    this.options = [];
  }

  remove(i: number,box:DisplayBox) {
    box.remove();
    this.options.splice(i,1);
    this.save();
  }

  load(){
    try{
      this.options = JSON.parse(localStorage.getItem(`${this.me.me.username}-data-analysis`));
      if(this.options===null) this.options = [];
      this.options.forEach(v=>{
        v.toLoad = true;
      })
    }catch (e) {
      this.options = [];
    }
  }

  save(){
    localStorage.setItem(`${this.me.me.username}-data-analysis`,JSON.stringify(this.options));
  }
}

